package com.wangyadong.hobby.thread.io;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2019/7/116:22
 **/
public abstract class TCPThrottledServer implements Runnable {
    ServerSocket server = null;
    Thread[] serverThreads;
    volatile boolean done;

    public synchronized void startServer(int port, int nThreads) throws IOException {
        server = new ServerSocket(port);
        serverThreads = new Thread[nThreads];
        for (int i = 0; i < serverThreads.length; i++) {
            serverThreads[i] = new Thread(this);
            serverThreads[i].start();
        }
    }

    public synchronized void setDone() {
        this.done = true;
    }


    @Override

    public void run() {
        while (!done) {
            try {
                Socket data = null;
                Socket accept = server.accept();
                run(data);
            } catch (IOException ioe) {
                System.out.println("Accept error " + ioe);
            }
        }
    }

    public void run(Socket data) {
    }
}
